﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Tsual.DataPipeline;
using Tsual.Wechat.Pipes;

namespace wechat_service
{
    public class DbpipeKonwnUser : IDataPipeDescription<string, DpmmKnownUser>
    {
        AppDbContext db;

        public DbpipeKonwnUser(AppDbContext db)
        {
            this.db = db;
        }

        public bool CanRead(DpmmKnownUser meta)
        {
            return true;
        }

        public bool CanWrite(string data, DpmmKnownUser meta)
        {
            return true;
        }

        public Task<DataPipeReadResult<string>> Read(DpmmKnownUser meta) => Task.Run(() =>
        {
            var r = db.Users.Where(t => t.WechatOpenid == meta.openid).Select(t => t.Id).FirstOrDefault();
            if (string.IsNullOrEmpty(r)) return DataPipeReadResult<string>.Notfound();
            return DataPipeReadResult<string>.Success(r);
        });

        public async Task<DataPipeWriteResult> Write(string data, DpmmKnownUser meta)
        {
            var user=db.Users.Find(data);
            if(user!=null)
            {
                user.WechatOpenid = meta.openid;
                db.Entry(user).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                await db.SaveChangesAsync();
            }
            return DataPipeWriteResult.Success();
        }
    }

}
